package com.atguigu.gmall.order.listener;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.gmall.common.constans.MqConst;
import com.atguigu.gmall.common.service.RabbitService;
import com.atguigu.gmall.model.enums.ProcessStatus;
import com.atguigu.gmall.order.service.OrderInfoService;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Date;
import java.util.Map;

@Component
@Slf4j
public class OrderInfoListener {
    @Autowired
    private OrderInfoService orderInfoService;
    @Autowired
    private RabbitService rabbitService;
    //
    @RabbitListener(queues = MqConst.QUEUE_ORDER_CANCEL)
    public void cancelOrder(Long orderId , Message message, Channel channel) throws IOException {
        System.out.println("接收的ID："+orderId+":时间："+new Date());
                orderInfoService.cancelOrder(orderId);
                channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
    }

    //支付成功之后 更新订单的状态
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = MqConst.QUEUE_PAYMENT_PAY,durable = "true",autoDelete = "false"),
            exchange = @Exchange(value = MqConst.EXCHANGE_DIRECT_PAYMENT_PAY),
            key = {MqConst.ROUTING_PAYMENT_PAY}
    ))
    public void updateOrder(Long orderId ,Message message , Channel channel )throws  IOException{
        System.out.println("接收的ID："+orderId);
        orderInfoService.updateOrderStatus(orderId , ProcessStatus.PAID);//从未支付改成已支付
        //发消息给仓库微服务   （仓库微服务不是同学写的）
        rabbitService.sendMessage(MqConst.EXCHANGE_DIRECT_WARE_STOCK,
                MqConst.ROUTING_WARE_STOCK, JSONObject.toJSONString(orderInfoService.initWareData(orderId)));
        //更新订单状态   //进度状态从已支付 改成 通知存储    订单状态是还是原来的已支付
        orderInfoService.updateOrderStatus(orderId,ProcessStatus.NOTIFIED_WARE);
        channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
    }


    //接收扣减库存的结果
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = MqConst.QUEUE_WARE_ORDER,durable = "true",autoDelete = "false"),
            exchange = @Exchange(value = MqConst.EXCHANGE_DIRECT_WARE_ORDER),
            key = {MqConst.ROUTING_WARE_ORDER}
    ))
    public void receiverResult(String jsonResult, Message message, Channel channel) throws IOException {
        System.out.println("接收的消息：" + jsonResult);
        Map map = JSONObject.parseObject(jsonResult, Map.class);
//        orderId	订单系统的订单ID
//        status	状态： ‘DEDUCTED’  (已减库存)
//                状态：  ‘OUT_OF_STOCK’  (库存超卖)
        Object status = map.get("status");
        if ("DEDUCTED".equals(status)) {
            //扣减成功 ，更新订单的状态机进度状态为代发货
            orderInfoService.updateOrderStatus(Long.parseLong(String.valueOf(map.get("orderId"))),
                    ProcessStatus.WAITING_DELEVER);
        } else {
            //库存异常
            log.error("库存异常");
            //调用通知工作人员的接口  转人工
        }

        //应答
        channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
    }
}
